package com.lalosoft.gastostarjetaweb.servlet;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lalosoft.gastostarjetaweb.Constants;
import com.lalosoft.gastostarjetaweb.dao.EmailDao;
import com.lalosoft.gastostarjetaweb.model.Email;
import com.lalosoft.gastostarjetaweb.util.DateUtils;

@SuppressWarnings("serial")
public class RecibirEmailServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger("RecibirEmailServlet");
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Properties props = new Properties();
		Session email = Session.getDefaultInstance(props, null);

		try {
			MimeMessage message = new MimeMessage(email, req.getInputStream());
			String summary = message.getSubject();
			String description = getText(message);
			Address[] addresses = message.getFrom();
			Email aEmail = new Email();
			aEmail.setAsunto(summary);
			aEmail.setFecha(DateUtils.now(Constants.NOW));
			aEmail.setRemitente(addresses[0].toString());
			aEmail.setMensaje(description);
			aEmail.setEstado(Constants.ESTADO_RECIBIDO);
			
			EmailDao.saveEmail(aEmail);
			
			log.log(Level.WARNING, "Se recibio correctamente el mail");

			
		} catch (Exception e) {
			log.log(Level.WARNING, "Error en recibir email: " + e.getMessage(), e);
		}
	}
	
	 private boolean textIsHtml = false;

	    
	 /**
	      * Return the primary text content of the message.
	      */

	     private String getText(Part p) throws
	                 MessagingException, IOException {
	         if (p.isMimeType("text/*")) {
	             String s = (String)p.getContent();
	             textIsHtml = p.isMimeType("text/html");
	             return s;
	         }

	         if (p.isMimeType("multipart/alternative")) {
	             // prefer html text over plain text
	             Multipart mp = (Multipart)p.getContent();
	             String text = null;
	             for (int i = 0; i < mp.getCount(); i++) {
	                 Part bp = mp.getBodyPart(i);
	                 if (bp.isMimeType("text/plain")) {
	                     if (text == null)
	                         text = getText(bp);
	                     continue;
	                 } else if (bp.isMimeType("text/html")) {
	                     String s = getText(bp);
	                     if (s != null)
	                         return s;
	                 } else {
	                     return getText(bp);
	                 }
	             }
	             return text;
	         } else if (p.isMimeType("multipart/*")) {
	             Multipart mp = (Multipart)p.getContent();
	             for (int i = 0; i < mp.getCount(); i++) {
	                 String s = getText(mp.getBodyPart(i));
	                 if (s != null)
	                     return s;
	             }
	         }

	         return null;
	     }

}
